package cn.elwy.rcp.ui.table.adapter;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

import cn.elwy.rcp.core.model.ui.tree.TreeNode;

public class TreeNodeContentAdapterImpl implements TreeNodeContentAdapter {

  private static final Object[] NO_CHILDREN = new Object[0];

  @Override
  public Object getParent(Object element) {
    if (element instanceof TreeNode) {
      return ((TreeNode) element).getParent();
    } else {
      return null;
    }
  }

  @Override
  public Object[] getChildren(Object element) {
    if ((element instanceof Collection)) {
      return ((Collection<?>) element).toArray();
    } else if (element instanceof Object[] || element instanceof Array) {
      return (Object[]) element;
    } else if (element instanceof TreeNode) {
      return ((TreeNode) element).getChildren();
    } else if (element instanceof Map) {
      return ((Map<?, ?>) element).values().toArray();
    }
    return NO_CHILDREN;
  }

  @Override
  public boolean hasChildren(Object element) {
    if (element instanceof TreeNode) {
      TreeNode treeNode = (TreeNode) element;
      if (treeNode.isDynamic()) {
        return true;
      } else {
        return treeNode.hasChildren();
      }
    } else {
      return getChildren(element).length > 0;
    }
  }

}
